global.BASE_DIR = __dirname;
global.CONF = BASE_DIR + '/conf/';
global.STATIC = BASE_DIR + '/static/';
global.VIEW = BASE_DIR + '/views/';
global.MODULE = BASE_DIR + '/modules/';
global.UPLOAD = STATIC + '/img/';

var url = require('url'),
  http = require('http'),
  formidable = require('formidable'),
  fs = require('fs'),
  sessionModule = require(MODULE + 'session.js'),
  httpParam = require(MODULE + 'httpParams.js'),
  indexModule = require(MODULE + 'index_Module.js'),
  staticModule = require(MODULE + 'static_Module.js');

http.createServer(function(req, res) {
  global.sessionLib = sessionModule.start(res, req);
  var pathname = url.parse(req.url).pathname;
  httpParam.init(req, res);
  if (!sessionLib['username']) {
    console.log(sessionLib);
    sessionLib['username'] = 'littleevil';
  }
  switch (pathname) {
    case '/favicon.ico':
      return;
    case '/upload':
      upload(res, req);
      break;
    case '/image':
      showImage(res, req);
      break;
    case '/':
      indexModule.goIndex(res);
      break;
    case '/index':
      indexModule.goIndex(res);
      break;
    case '/show':
      show(res);
      break;
    default:
      staticModule.getStaticFile(pathname, res);
  }
}).listen(3000);
console.log('server start at http://127.0.0.1:3000');

function upload(res, req) {
  var readPath = VIEW + url.parse('show.html').pathname;
  var uploadPage = fs.readFileSync(readPath);
  var form = new formidable.IncomingForm();
  form.parse(req, function(error, fields, files) {
    var originalName = files.image.name;
    var fileName = fields.title + originalName.substring(originalName.indexOf('.'));
    // 可读流
    var readerStream = fs.createReadStream(files.image.path);
    // 可写流
    var writerStream = fs.createWriteStream(UPLOAD + fileName);
    readerStream.pipe(writerStream);
    // fs.renameSync(files.image.path, UPLOAD + fileName);
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(uploadPage);
  });
}
